package leetcode.code1408;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import leetcode.IDebug;

//执行用时：9 ms, 在所有 Java 提交中击败了6.07%的用户
//
//内存消耗：42 MB, 在所有 Java 提交中击败了5.10%的用户
//
//通过测试用例：67 / 67
public class Solution6 implements IDebug {

	public List<String> stringMatching(String[] words) {
		int len = words.length;
		List<String> ans = new ArrayList<>();
		for (int i = 0; i < len; i++) {
			for (int j = 0; j < len; j++) {
				if (i != j && words[j].indexOf(words[i]) >= 0) {
					ans.add(words[i]);
					break;
				}
			}
		}
		return ans;
	}

	public List<String> stringMatching2(String[] words) {
		int len = words.length;
		List<String> ans = new ArrayList<>();
		for (int i = 0; i < len; i++) {
			for (int j = 0; j < len; j++) {
				if (i != j && this.kmp(words[j], words[i])) {
					ans.add(words[i]);
					break;
				}
			}
		}
		return ans;
	}

	public boolean kmp(String haystack, String needle) {
		if (haystack.length() <= needle.length()) {
			return false;
		}
		char[] chars1 = haystack.toCharArray();
		char[] chars2 = needle.toCharArray();
		int len1 = chars1.length;
		int len2 = chars2.length;
		int[] p = new int[len2];
		// p中m位置记录数值n,表示[0,n-1]的字符串同[m-n+1,m]字符串相同
		for (int i = 1, j = 0; i < len2 && j < len2; i++) {
			while (j > 0 && chars2[j] != chars2[i]) {
				j = p[j - 1];
			}
			if (chars2[i] == chars2[j]) {
				j++;
			}
			p[i] = j;
		}
		for (int i = 0, j = 0; i < len1 && j < len2; i++) {
			while (j > 0 && chars2[j] != chars1[i]) {
				j = p[j - 1];
			}
			if (chars2[j] == chars1[i]) {
				j++;
			}
			if (j == len2) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution6 so = new Solution6();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
